<?php
namespace app\pay\controller\juyin;

class Orderquery extends Base
{
    // 订单查询
    public function orderInfo() {
        $data = input('post.');     // 获取客户端POST过来的参数
        // 验证签名
        $res = $this->verifySign($data, false);
        if($res) {
            $this->request();
            // 组装POST到聚银的数据
            if($data['compatible']) {
                // 版本2
                $postToJuyin = array(
                    'merchant_id'    => $this->cfg->C('merchantId', false), // 更改商户号为聚银商户号
                    'compatible'     => $data['compatible'],
                    'pay_orderid'      => $data['pay_orderid'],
                );
            } else {
                // 版本1
                $postToJuyin = array(
                    'merchant_id'    => $this->cfg->C('merchantId', false), // 更改商户号为聚银商户号
                    'pay_orderid'      => $data['pay_orderid'],
                );
            }
            /*
             * 1.将订单信息保存到数据库中
             * 2.验证聚银签名并向聚银官方接口发起POST请求
             */
            $ret = $this->requestData($postToJuyin, 'orderQuery', false);
            $retData = json_decode($ret, true);
            // 接收聚银返回的数据并组装
            $result = $this->responseData($data['merchant_id'], $retData);
            return $result;
        } else {
            return $res;
        }
    }

    // 接收聚银返回的数据并组装
    public function responseData($merchantId, $data) {
        if($data['3orderid']) {
            // 将订单信息保存到数据库中
//            $this->payBisOrderUpdate($data);
            // 数据组装
            $result = array(
                '1out_trade_id' => $data['1out_trade_id'],
                '2memberid'     => $merchantId . 'A123', 
                '3orderid'      => $data['3orderid'],
                '4amount'       => $data['4amount'],
                '5applydate'    => $data['5applydate'],
                '6status'       => $data['6status'],
                '7tongdao'      => $data['7tongdao'],
                '8actAmt'       => $data['8actAmt'],
                'signature'     => $data['signature'],
            );
            // 生成新的签名
            $newJuyinSignVal = $this->payRequest->createJuyinSign($result, false);
            $result['signature'] = $newJuyinSignVal;
        } else {
            $result = array(
                'code' => $data['code'],
                'msg'  => $data['msg']
            );
        }
        return json_encode($result, true);
    }
    
    // 订单信息添加
    public function payBisOrderUpdate($data) {
        $orderInfo = array(
            'pay_orderid'     => $data['pay_orderid'],
            'merchant_id'     => $data['merchant_id'], // 更改商户号为聚银商户号
            'pay_amount'      => $data['pay_amount'],
            'actual_amount'   => $data['pay_amount'] - 200,
            'pay_tradetype'   => $data['pay_tradetype'],
            'payment_time'    => null,
        );
        model('PayBisOrder')->add($orderInfo);
    }
}

